package com.after.saas.file.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @Description
 * @Classname PdfUtil
 * @Author hjchen
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2023/4/26 16:06
 */

@Slf4j
public class PdfUtil {
    /**
     * 校验pdf文件是否包含js脚本
     **/
    public static boolean containsJavaScript(String path) {
        try {
            return containsJavaScript(PDDocument.load(new File(path)));
        } catch (IOException e) {
            log.error("校验pdf文件异常：{}", e.getMessage());
        }
        return false;
    }

    /**
     * 校验pdf文件是否包含js脚本
     **/
    public static boolean containsJavaScript(InputStream input) {
        try {
            return containsJavaScript(PDDocument.load(input));
        } catch (IOException e) {
            log.error("校验pdf文件异常：{}", e.getMessage());
        }
        return false;
    }

    /**
     * 校验pdf文件是否包含js脚本
     **/
    public static boolean containsJavaScript(PDDocument document) {
        Optional<COSObject> pdfJs = document.getDocument().getObjects().stream().filter(cosObject -> {
            String str = Optional.ofNullable(cosObject.getObject()).map(Object::toString).orElse("");
            return str.contains("JavaScript") || str.contains("COSName{JS}");
        }).findAny();
        return pdfJs.isPresent();
    }

    public static void createPdf(String filePath) {
        try {
            //Loading an existing file
            File file = new File(filePath);
            PDDocument document = PDDocument.load(file);
            String javaScript = "app.alert('this is an example');";
            //Creating PDActionJavaScript object
            PDActionJavaScript PDAjavascript = new PDActionJavaScript(javaScript);
            //Embedding java script
            document.getDocumentCatalog().setOpenAction(PDAjavascript);
            document.save(new File("D:\\tmp\\simple-js.pdf"));
            System.out.println("javascript=" + PDAjavascript.getCOSObject().toString());
            //Closing the document
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //更多请阅读：https://www.imangodoc.com/36529.html
    }

    public static void main(String[] args) {
        //Loading an existing document
        String newPath = "D:\\tmp\\test.pdf";
        String path = "D:\\tmp\\simple-js.pdf";
//        createPdf(newPath);
        System.out.println(containsJavaScript(path));
    }


}
